<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>对话 - 白菜知识库AI系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        :root { --theme-color: #28a745; --border-color: #ddd; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; background-color: #f4f4f9; display: flex; flex-direction: column; height: 100vh; }
        .header { background-color: #fff; padding: 0 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; height: 60px; flex-shrink: 0; }
        .header h1 { font-size: 20px; margin: 0; color: #333; }
        .header .user-controls button { margin-left: 10px; padding: 8px 16px; border: 1px solid var(--border-color); background-color: #f8f9fa; cursor: pointer; border-radius: 5px; font-size: 14px; }
        .header .user-controls button:hover { background-color: #e2e6ea; }
        .chat-container { flex-grow: 1; overflow-y: auto; padding: 20px; }
        .message { margin-bottom: 15px; display: flex; flex-direction: column; }
        .message .bubble { max-width: 75%; padding: 12px 18px; border-radius: 20px; line-height: 1.6; word-wrap: break-word; }
        .message.user { align-items: flex-end; }
        .message.user .bubble { background-color: var(--theme-color); color: white; }
        .message.ai { align-items: flex-start; }
        .message.ai .bubble { background-color: #fff; color: #333; border: 1px solid #e9ecef; }
        .input-area { display: flex; padding: 15px; border-top: 1px solid var(--border-color); background-color: #fff; flex-shrink: 0; }
        #chat-input { flex-grow: 1; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; resize: none; font-size: 16px; }
        #send-btn { margin-left: 10px; padding: 12px 25px; background-color: var(--theme-color); color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; }
        #send-btn:hover { background-color: #218838; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.4); justify-content: center; align-items: center; }
        .modal-content { background-color: white; padding: 25px; border-radius: 8px; width: 550px; max-width: 95%; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .modal-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border-color); padding-bottom: 15px; margin-bottom: 20px; }
        .modal-header h2 { margin: 0; }
        .close-btn { cursor: pointer; font-size: 28px; border: none; background: none; font-weight: bold; color: #aaa; }
        .close-btn:hover { color: #333; }
        #doc-list { list-style: none; padding: 0; max-height: 250px; overflow-y: auto; border: 1px solid #eee; border-radius: 5px; }
        #doc-list li { display: flex; justify-content: space-between; align-items: center; padding: 12px; border-bottom: 1px solid #eee; }
        #doc-list li:last-child { border-bottom: none; }
        .delete-doc-btn { color: #dc3545; cursor: pointer; font-weight: bold; padding: 5px; }
        .upload-section { margin-bottom: 20px; padding: 15px; border: 2px dashed #eee; border-radius: 5px; text-align: center; }
        .upload-section input[type="file"] { display: none; }
        .upload-label { background-color: var(--theme-color); color: white; padding: 10px 15px; border-radius: 5px; cursor: pointer; display: inline-block; }
        .upload-label:hover { background-color: #218838; }
        #file-name { margin-top: 10px; color: #555; }
        .loading { color: #666; text-align: center; padding: 20px; }
    </style>
</head>
<body>

<div class="header">
    <h1 id="welcome-message">你好, ...</h1>
    <div class="user-controls">
        <button id="manage-kb-btn">知识库管理</button>
        <form id="logout-form" action="/logout" method="post" style="display: inline;">
            <button type="submit">退出登录</button>
        </form>
    </div>
</div>

<div class="chat-container" id="chat-container">
    <div class="message ai"><div class="bubble">你好！有什么可以帮助你的吗？可以先点击右上角的"知识库管理"上传你自己的文档。</div></div>
</div>

<div class="input-area">
    <textarea id="chat-input" placeholder="在这里输入你的问题..." rows="1"></textarea>
    <button id="send-btn">发送</button>
</div>

<!-- 知识库管理 Modal -->
<div id="kb-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>知识库管理</h2>
            <button class="close-btn">&times;</button>
        </div>
        <div class="upload-section">
            <label for="file-upload" class="upload-label">选择文件</label>
            <input type="file" id="file-upload">
            <p id="file-name">未选择任何文件</p>
            <button id="upload-btn" style="padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">确认上传</button>
        </div>
        <hr style="margin: 20px 0;">
        <h3>已上传文档</h3>
        <ul id="doc-list"><li class="loading">正在加载文档列表...</li></ul>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const welcomeMessage = document.getElementById('welcome-message');
        const chatContainer = document.getElementById('chat-container');
        const chatInput = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');
        const kbModal = document.getElementById('kb-modal');
        const manageKbBtn = document.getElementById('manage-kb-btn');
        const closeBtn = kbModal.querySelector('.close-btn');
        const docList = document.getElementById('doc-list');
        const fileUpload = document.getElementById('file-upload');
        const uploadBtn = document.getElementById('upload-btn');
        const fileNameSpan = document.getElementById('file-name');

        let currentUser = null;
        let chatHistory = [];

        // --- 获取用户信息并验证登录状态 ---
        fetch('/api/user/me', {
            credentials: 'include'
        })
        .then(response => {
            if (response.status === 401) {
                window.location.href = '/login';
                return Promise.reject('User not authenticated');
            }
            return response.json();
        })
        .then(user => {
            currentUser = user;
            welcomeMessage.textContent = `你好, ${user.username}`;
        })
        .catch(error => {
            console.error('Error fetching user info:', error);
            if (error !== 'User not authenticated') {
                welcomeMessage.textContent = '无法加载用户信息';
            }
        });

        function addMessage(sender, text) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message', sender);
            const bubbleDiv = document.createElement('div');
            bubbleDiv.classList.add('bubble');
            bubbleDiv.textContent = text;
            messageDiv.appendChild(bubbleDiv);
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        async function handleSendMessage() {
            const question = chatInput.value.trim();
            if (!question) return;

            addMessage('user', question);
            chatInput.value = '';

            try {
                const response = await fetch(`/api/knowledge-manage/retrieve?query=${encodeURIComponent(question)}&username=${encodeURIComponent(currentUser.username)}`, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                const result = await response.json();

                if (!response.ok || !result.success) {
                    throw new Error(result.message || '服务器响应异常');
                }

                const answer = extractAnswerFromResponse(result.data);
                addMessage('ai', answer || '抱歉，未能从您的知识库中找到相关答案。');
            } catch (error) {
                console.error('Error:', error);
                addMessage('ai', `抱歉，我遇到了一点问题: ${error.message}`);
            }
        }

        // 从RetrieveResponse中提取答案内容
        function extractAnswerFromResponse(retrieveResponseBody) {
            if (retrieveResponseBody && retrieveResponseBody.data && retrieveResponseBody.data.nodes && retrieveResponseBody.data.nodes.length > 0) {
                return retrieveResponseBody.data.nodes.map(node => node.text).join('\n\n');
            }
            return null;
        }

        sendBtn.addEventListener('click', handleSendMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
            }
        });

        // 自动调整输入框高度
        chatInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        manageKbBtn.addEventListener('click', () => {
            kbModal.style.display = 'flex';
            loadDocuments();
        });

        closeBtn.addEventListener('click', () => kbModal.style.display = 'none');

        window.addEventListener('click', (e) => {
            if (e.target === kbModal) kbModal.style.display = 'none';
        });

        async function loadDocuments() {
            docList.innerHTML = '<li class="loading">正在加载文档列表...</li>';

            try {
                const response = await fetch(`/api/knowledge-manage/documents?username=${encodeURIComponent(currentUser.username)}`, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                const result = await response.json();

                if (!response.ok || !result.success) {
                    if (result.message && result.message.includes("尚未创建知识库")) {
                        docList.innerHTML = '<li class="loading">您还没有上传任何文档。</li>';
                        return;
                    }
                    throw new Error(result.message || '无法获取文档列表');
                }
                
                const documents = result.data;
                docList.innerHTML = '';

                if (!documents || documents.length === 0) {
                    docList.innerHTML = '<li class="loading">您还没有上传任何文档。</li>';
                } else {
                    documents.forEach(doc => {
                        const li = document.createElement('li');
                        li.innerHTML = `
                            <span>${doc.name || doc.id}</span>
                            <span class="delete-doc-btn" title="删除文档" data-doc-id="${doc.id}">×</span>
                        `;
                        docList.appendChild(li);
                    });

                    document.querySelectorAll('.delete-doc-btn').forEach(btn => {
                        btn.addEventListener('click', (e) => {
                            const docId = e.currentTarget.getAttribute('data-doc-id');
                            deleteDocument(docId);
                        });
                    });
                }
            } catch (error) {
                console.error('Error loading documents:', error);
                docList.innerHTML = `<li class="loading">加载失败: ${error.message}</li>`;
            }
        }

        async function deleteDocument(docId) {
            if (!confirm(`确定要删除文档 "${docId}" 吗？`)) return;

            try {
                const formData = new FormData();
                formData.append('documentId', docId);
                formData.append('username', currentUser.username);

                const response = await fetch(`/api/knowledge-manage/delete`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: new URLSearchParams(formData)
                });

                const result = await response.json();

                if (!response.ok || !result.success) {
                    throw new Error(result.message || '删除失败');
                }

                alert('文档删除成功！');
                loadDocuments();
            } catch (error) {
                console.error('Delete error:', error);
                alert(`删除失败: ${error.message}`);
            }
        }

        fileUpload.addEventListener('change', () => {
            fileNameSpan.textContent = fileUpload.files.length > 0
                ? `已选择: ${fileUpload.files[0].name}`
                : '未选择任何文件';
        });

        uploadBtn.addEventListener('click', async () => {
            const file = fileUpload.files[0];
            if (!file) {
                alert('请先选择一个文件。');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);
            formData.append('username', currentUser.username);

            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';

            try {
                const response = await fetch('/api/knowledge-manage/upload', {
                    method: 'POST',
                    credentials: 'include',
                    body: formData
                });

                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.message || '上传失败');
                }

                alert('文档上传成功！');
                loadDocuments();
                fileUpload.value = '';
                fileNameSpan.textContent = '未选择任何文件';
            } catch (error) {
                console.error('Upload error:', error);
                alert(`上传失败: ${error.message}`);
            } finally {
                uploadBtn.disabled = false;
                uploadBtn.textContent = '确认上传';
            }
        });
    });
</script>

</body>

</html>